package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private WeChatPayUtil weChatPayUtil;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WebSocketServer webSocketServer;


    /*@Value("${sky.shop.address}")
    private String shopAddress;

    @Value("${sky.baidu.ak}")
    private String ak;*/


    /*
     *
     * 用户端订单提交
     *
     * */
    @Transactional
    @Override
    public OrderSubmitVO orderSubmit(OrdersSubmitDTO ordersSubmitDTO) {

        //处理各种业务异常(地址簿为空、购物车数据为空)
        //处理地址簿为空异常
        Long addressBookId = ordersSubmitDTO.getAddressBookId();
        AddressBook addressBook = addressBookMapper.getById(addressBookId);
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        //检查配送范围
        /*checkOutOfRange(addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail());*/


        //处理购物车数据为空异常
        Long userId = BaseContext.getCurrentId();
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.select(userId);
        if (shoppingCartList == null || shoppingCartList.size() == 0) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }


        //向订单表插入1条数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setOrderTime(LocalDateTime.now());
        orders.setAddress(addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setUserId(userId);
        orders.setPayStatus(Orders.UN_PAID);
        orders.setPhone(addressBook.getPhone());

        orderMapper.insert(orders);

        //向订单明细表插入n条数据

        List<OrderDetail> orderDetailList = new ArrayList<>();

        for (ShoppingCart shoppingCart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        }

        orderDetailMapper.insertBatch(orderDetailList);


        //清空当前用户的购物车数据
        shoppingCartMapper.deleteAll(userId);

        //封装VO返回结果
        OrderSubmitVO orderSubmitVO = new OrderSubmitVO();
        orderSubmitVO.setId(orders.getId());
        orderSubmitVO.setOrderTime(orders.getOrderTime());
        orderSubmitVO.setOrderNumber(orders.getNumber());
        orderSubmitVO.setOrderAmount(orders.getAmount());

        return orderSubmitVO;
    }


    /**
     * 用户端订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) {
        OrderPaymentVO vo = new OrderPaymentVO();
        vo.setNonceStr("666");
        vo.setPaySign("hhh");
        vo.setPackageStr("prepay_id=wx");
        vo.setSignType("RSA");
        vo.setTimeStamp("1670380960");

        //用websocket向客户端浏览器推送消息
        Map map = new HashMap<>();
        map.put("type",1);
        map.put("orderId",ordersPaymentDTO.getOrderNumber());
        map.put("content","订单号:" +ordersPaymentDTO.getOrderNumber());

        String jsonString = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(jsonString);


        return vo;
    }

    /**
     * 用户端支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
    }


    /*
     *
     * 用户端历史订单（分页）查询
     *
     * */
    @Override
    public PageResult queryHistoryOrders(int page, int pageSize, Integer status) {

        //需要用pagehelper插件进行分页
        PageHelper.startPage(page, pageSize);

        //需要根据DTO获取orders的数据
        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();

        Long userId = BaseContext.getCurrentId();
        ordersPageQueryDTO.setUserId(userId);
        ordersPageQueryDTO.setStatus(status);

        Page<Orders> ordersPage = orderMapper.queryHistoryOrders(ordersPageQueryDTO);

        //需要获取orderdetail的数据
        List<OrderVO> orderVOList = new ArrayList();

        if (ordersPage != null && ordersPage.getTotal() > 0) {
            for (Orders orders : ordersPage) {

                Long orderId = orders.getId();
                List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(orderId);

                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                orderVO.setOrderDetailList(orderDetails);

                orderVOList.add(orderVO);
            }
        }

        PageResult pageResult = new PageResult();
        pageResult.setTotal(ordersPage.getTotal());
        pageResult.setRecords(orderVOList);

        return pageResult;
    }


    /*
     *
     * 用户端根据订单id查询订单详情
     *
     * */
    @Override
    public OrderVO getOrderDetailByOrderId(Long id) {

        // 根据id查询订单
        Orders orders = orderMapper.getById(id);

        // 查询该订单对应的菜品/套餐明细
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());

        // 将该订单及其详情封装到OrderVO并返回
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(orderDetailList);

        return orderVO;
    }


    /*
     *
     * 用户端根据订单id取消订单
     *
     * */
    @Override
    public void cancel(Long id) {

        //获得订单信息
        Orders orders = orderMapper.getById(id);


        // 校验订单是否存在
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }


        //判断订单是否能取消
        if (orders.getStatus() > 2) {
            if (orders.getStatus() == Orders.CONFIRMED) {
                log.info("商家已接单，如需取消订单请电话沟通商家进行取消操作！");
            } else if (orders.getStatus() == orders.DELIVERY_IN_PROGRESS) {
                log.info("订单正在派送，如需取消订单请电话沟通商家进行取消操作！");
            }
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }


        //待支付和待接单状态下，用户可直接取消订单
        if (orders.getStatus() == Orders.PENDING_PAYMENT || orders.getStatus() == Orders.TO_BE_CONFIRMED) {
            //如果在待接单状态下取消订单，需要给用户退款
            if (orders.getStatus() == Orders.TO_BE_CONFIRMED) {
                orders.setPayStatus(Orders.REFUND);
            }
            //取消订单后需要将订单状态修改为“已取消”
            orders.setStatus(Orders.CANCELLED);
            orders.setCancelReason("用户取消订单");
            orders.setCancelTime(LocalDateTime.now());
        }


        /*//商家已接单状态下，用户取消订单需电话沟通商家
        if (orders.getStatus() == Orders.CONFIRMED) {
            log.info("商家已接单，如需取消订单请电话沟通商家进行取消操作！");
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }


        //派送中状态下，用户取消订单需电话沟通商家
        if (orders.getStatus() == orders.DELIVERY_IN_PROGRESS) {
            log.info("商家已接单，如需取消订单请电话沟通商家进行取消操作！");
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //订单已完成状态下，用户不能取消订单
        if (orders.getStatus() == Orders.COMPLETED) {
            log.info("订单已完成，不能取消！");
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //订单已取消状态下，用户不能取消订单
        if (orders.getStatus() == Orders.CANCELLED) {
            log.info("订单已取消，请勿重复操作！");
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }*/


        orderMapper.update(orders);
    }


    /*
     *
     * 用户端再来一单
     *
     * */
    @Override
    public void repetitionById(Long id) {
        /*//根据订单id重新生成一份订单
        Orders order = orderMapper.getById(id);
        Orders newOrder = new Orders();
        BeanUtils.copyProperties(order,newOrder);
        newOrder.setNumber(String.valueOf(System.currentTimeMillis()));
        newOrder.setStatus(Orders.PENDING_PAYMENT);
        newOrder.setOrderTime(LocalDateTime.now());
        newOrder.setPayStatus(Orders.UN_PAID);

        orderMapper.insert(newOrder);*/


        //再来一单就是将原订单中的商品重新加入到购物车中
        //由于购物车数据已被清空，因此需要重新想办法拿到对应订单的购物车数据
        List<ShoppingCart> shoppingCartList = new ArrayList<>();

        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);

        Long userId = BaseContext.getCurrentId();

        for (OrderDetail orderDetail : orderDetailList) {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail, shoppingCart);
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartList.add(shoppingCart);
        }

        //将购物车数据重新写入
        for (ShoppingCart shoppingCart : shoppingCartList) {
            shoppingCartMapper.insert(shoppingCart);
        }

    }


    /*
     *
     * 管理端订单搜索
     *
     * */
    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {

        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());

        Page<Orders> page = orderMapper.queryHistoryOrders(ordersPageQueryDTO);

        long total = page.getTotal();
        List<Orders> ordersList = page.getResult();

        List<OrderVO> orderVOList = new ArrayList<>();

        //需要获取订单的商品
        for (Orders orders : ordersList) {
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(orders, orderVO);

            String orderDishes = getOrderDishesStr(orders);

            // 将订单商品信息封装到orderVO中，并添加到orderVOList
            orderVO.setOrderDishes(orderDishes);
            orderVOList.add(orderVO);

        }

        PageResult pageResult = new PageResult(total, orderVOList);

        return pageResult;
    }


    /*
     *
     * 管理端各个状态的订单数量统计
     *
     * */
    @Override
    public OrderStatisticsVO statistics() {

        List<Orders> toBeConfirmed = orderMapper.selectByStatus(Orders.TO_BE_CONFIRMED);
        List<Orders> confirmed = orderMapper.selectByStatus(Orders.CONFIRMED);
        List<Orders> deliveryInProgress = orderMapper.selectByStatus(Orders.DELIVERY_IN_PROGRESS);

        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        //待接单数量
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed.size());
        //待派送数量
        orderStatisticsVO.setConfirmed(confirmed.size());
        //派送中数量
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress.size());

        return orderStatisticsVO;
    }


    /*
     *
     * 管理端根据订单id查询订单详情
     *
     * */
    @Override
    public OrderVO getOrderDetailById(Long id) {

        OrderVO orderVO = new OrderVO();
        Orders orders = orderMapper.getById(id);
        BeanUtils.copyProperties(orders, orderVO);

        //获取orderDishes
        String orderDishes = getOrderDishesStr(orders);
        orderVO.setOrderDishes(orderDishes);

        //获取orderDetailList
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);
        orderVO.setOrderDetailList(orderDetailList);

        return orderVO;
    }


    /*
     *
     * 管理端接单
     *
     * */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = orderMapper.getById(ordersConfirmDTO.getId());
        orders.setStatus(Orders.CONFIRMED);
        orderMapper.update(orders);
    }


    /*
     *
     * 管理端拒单
     *
     * */
    @Override
    public void reject(OrdersRejectionDTO ordersRejectionDTO) {

        Orders orders = orderMapper.getById(ordersRejectionDTO.getId());

        //只有订单处于“待接单”状态时可以执行拒单操作
        if (orders.getStatus() != Orders.TO_BE_CONFIRMED) {
            log.info("当前订单状态不是待接单状态，操作失败！");
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //商家拒单时，如果用户已经完成了支付，需要为用户退款
        if (orders.getPayStatus() == Orders.PAID) {
            orders.setPayStatus(Orders.REFUND);
        }

        orders.setStatus(Orders.CANCELLED);
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }


    /*
     *
     * 管理端取消订单
     *
     * */
    @Override
    public void adminCancel(OrdersCancelDTO ordersCancelDTO) {
        Orders orders = orderMapper.getById(ordersCancelDTO.getId());

        //已完成或已取消或待接单的订单不能进行取消操作
        if (orders.getStatus() == Orders.TO_BE_CONFIRMED || orders.getStatus() == Orders.COMPLETED || orders.getStatus() == Orders.CANCELLED) {
            log.info("已完成或已取消或待接单的订单不能进行取消操作，操作失败！");
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //商家取消时，如果用户已经完成了支付，需要为用户退款
        if (orders.getPayStatus() == Orders.PAID) {
            orders.setPayStatus(Orders.REFUND);
        }

        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }


    /*
     *
     * 管理端派送订单
     *
     * */
    @Override
    public void delivery(Long id) {
        Orders orders = orderMapper.getById(id);

        //只有订单处于“待派送”状态时可以执行派送操作
        if (orders.getStatus() != Orders.CONFIRMED) {
            log.info("当前订单状态不是待派送状态，操作失败！");
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);

        orderMapper.update(orders);
    }


    /*
     *
     * 管理端完成订单
     *
     * */
    @Override
    public void complete(Long id) {
        Orders orders = orderMapper.getById(id);

        //只有订单处于“派送中”状态时可以执行完成操作
        if (orders.getStatus() != Orders.DELIVERY_IN_PROGRESS) {
            log.info("当前订单状态不是派送中状态，操作失败！");
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        orders.setStatus(Orders.COMPLETED);
        orders.setDeliveryTime(LocalDateTime.now());

        orderMapper.update(orders);
    }



    /*
     *
     * 催单
     *
     * */
    @Override
    public void reminder(Long id) {
        Orders orders = orderMapper.getById(id);

        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Map map = new HashMap<>();
        map.put("type",2);
        map.put("orderId",id);
        map.put("content", "订单号:" + orders.getNumber());

        String json = JSON.toJSONString(map);

        webSocketServer.sendToAllClient(json);
    }


    /**
     * 根据订单id获取菜品信息字符串
     *
     * @param orders
     * @return
     */
    private String getOrderDishesStr(Orders orders) {
        // 查询订单菜品详情信息（订单中的菜品和数量）
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());

        // 将每一条订单菜品信息拼接为字符串（格式：宫保鸡丁*3；）
        List<String> orderDishList = orderDetailList.stream().map(x -> {
            String orderDish = x.getName() + "*" + x.getNumber() + ";";
            return orderDish;
        }).collect(Collectors.toList());

        // 将该订单对应的所有菜品信息拼接在一起
        return String.join("", orderDishList);
    }


    /**
     * 检查客户的收货地址是否超出配送范围
     *
     * @param address
     */
    /*private void checkOutOfRange(String address) {
        Map map = new HashMap();
        map.put("address", shopAddress);
        map.put("output", "json");
        map.put("ak", ak);

        //获取店铺的经纬度坐标
        String shopCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        JSONObject jsonObject = JSON.parseObject(shopCoordinate);
        if (!jsonObject.getString("status").equals("0")) {
            throw new OrderBusinessException("店铺地址解析失败");
        }

        //数据解析
        JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
        String lat = location.getString("lat");
        String lng = location.getString("lng");
        //店铺经纬度坐标
        String shopLngLat = lat + "," + lng;

        map.put("address", address);
        //获取用户收货地址的经纬度坐标
        String userCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        jsonObject = JSON.parseObject(userCoordinate);
        if (!jsonObject.getString("status").equals("0")) {
            throw new OrderBusinessException("收货地址解析失败");
        }

        //数据解析
        location = jsonObject.getJSONObject("result").getJSONObject("location");
        lat = location.getString("lat");
        lng = location.getString("lng");
        //用户收货地址经纬度坐标
        String userLngLat = lat + "," + lng;

        map.put("origin", shopLngLat);
        map.put("destination", userLngLat);
        map.put("steps_info", "0");

        //路线规划
        String json = HttpClientUtil.doGet("https://api.map.baidu.com/directionlite/v1/driving", map);

        jsonObject = JSON.parseObject(json);
        if (!jsonObject.getString("status").equals("0")) {
            throw new OrderBusinessException("配送路线规划失败");
        }

        //数据解析
        JSONObject result = jsonObject.getJSONObject("result");
        JSONArray jsonArray = (JSONArray) result.get("routes");
        Integer distance = (Integer) ((JSONObject) jsonArray.get(0)).get("distance");

        if (distance > 5000) {
            //配送距离超过5000米
            throw new OrderBusinessException("超出配送范围");
        }
    }*/
}
